package com.citic.netty.server.handler;

import com.citic.netty.common.protocol.request.MessageRequestPacket;
import com.citic.netty.common.protocol.response.MessageResponsePacket;
import com.citic.netty.common.protocol.session.Session;
import com.citic.netty.common.utils.SessionUtil;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@ChannelHandler.Sharable
public class MessageRequestHandler extends SimpleChannelInboundHandler<MessageRequestPacket>{

    public static final MessageRequestHandler INSTANCE = new MessageRequestHandler();

    private MessageRequestHandler() {

    }
    
	/**
	 * @param ChannelHandlerContext		发送人的上下文
	 * @param MessageRequestPacket		发送人要发送的消息体
	 */
	@Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageRequestPacket messageRequestPacket) {
		/**
		 * 根据发送人的channel获取发送人的session
		 */
        Session session = SessionUtil.getSession(ctx.channel());

        MessageResponsePacket messageResponsePacket = new MessageResponsePacket();
        messageResponsePacket.setFromUserId(session.getUserId());
        messageResponsePacket.setFromUserName(session.getUsername());
        messageResponsePacket.setMessage(messageRequestPacket.getMessage());
        System.err.println(session.getUsername() + ": 在发消息");
        
        /**
         * 根据接收人的ID获取接收人的Channel
         */
        Channel toUserChannel = SessionUtil.getChannel(messageRequestPacket.getToUserId());
        if(toUserChannel != null && SessionUtil.hasLogin(toUserChannel)) {
            toUserChannel.writeAndFlush(messageResponsePacket);
        }  else {
            System.err.println("[" + messageRequestPacket.getToUserId() + "] 不在线，发送失败!");
        }
    }
}
